 <template>
  <d2-container>
    <template slot="header">
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1" title="更多操作">
          <el-form :inline="true" :model="listQuery" size="mini" style="margin-bottom: -18px;">
            <el-row>
              <el-col :span="24">
                <el-form-item style="float: left">
                  <el-button @click="handleCreate" type="primary" icon="el-icon-plus">新 增</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="分类" prop="username">
              <el-select v-model="listQuery.client_type" placeholder="请选择">
                <el-option
                  v-for="item in options3"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="拨打状态">
              <el-select v-model="listQuery.callFlag" placeholder="请选择">
                <el-option
                  v-for="item in options7"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="车牌" prop="username">
              <el-input
                @keyup.enter.native="handleFilter"
                style="width: 200px;"
                placeholder
                v-model="listQuery.car_no"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="车主" prop="username">
              <el-input
                @keyup.enter.native="handleFilter"
                style="width: 200px;"
                placeholder
                v-model="listQuery.car_owner"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="车型" prop="username">
              <el-input
                @keyup.enter.native="handleFilter"
                style="width: 200px;"
                placeholder
                v-model="listQuery.vehicle_type"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="商业险到期日期" prop="username">
              <el-date-picker
                v-model="listQuery.viEndDate"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="交强险到期日期" prop="username">
              <el-date-picker
                v-model="listQuery.clivtaEndDate"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="default" @click="handleFilter" icon="el-icon-search">搜 索</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </template>

    <!-- table表格 -->
    <el-table
      ref="multipleTable"
      :key="tableKey"
      :data="list"
      highlight-current-row
      stripe
      style="width: 100%;"
      sortable="custom"
      height="100%"
    >
      <!-- <el-table-column type="selection" width="55"></el-table-column> -->
      <el-table-column type="index" align="center" label="序号" width="60"></el-table-column>
      <el-table-column align="center" label="保险公司" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.insurerName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车牌号" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.carNo}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车型" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.vehicleType}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分类" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.label}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车主" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.carOwner}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="商业险到期日期"
        show-overflow-tooltip
        width="150"
        sortable
        prop="clivtaEndDate"
      >
        <template slot-scope="scope">
          <span>{{scope.row.viEndDate | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="交强险到期日期"
        show-overflow-tooltip
        width="150"
        sortable
        prop="clivtaEndDate"
      >
        <template slot-scope="scope">
          <span>{{scope.row.clivtaEndDate | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.note}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.modificationDate | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.createDate | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后一次通话时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.lastCallTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="handleDetial(scope.row)"
            icon="fa fa-bar-chart"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- footer 分页条 -->
    <template slot="footer">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page"
        :page-sizes="[50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: -10px;"
      ></el-pagination>
    </template>
    <!-- 新增客户信息弹框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="80px" size="mini">
        <el-row style="width:100%">
          <el-col :span="12">
            <el-form-item label="分类" placeholder prop="carNo">
              <el-select v-model="value3" placeholder="请选择">
                <el-option
                  v-for="item in options3"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌" placeholder prop="carNo">
              <el-input v-model="form.carNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车架" placeholder prop="vehicleNo">
              <el-input v-model="form.vehicleNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机" placeholder prop="engineNumber">
              <el-input v-model="form.engineNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车主" placeholder prop="carOwner">
              <el-input v-model="form.carOwner"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="被保险人" placeholder prop="carOwner">
              <el-input v-model="form.insured"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" placeholder prop="carOwner">
              <el-input v-model="form.insuredIdCard"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" placeholder prop="mobilePhone">
              <el-input v-model="form.mobilePhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话2" placeholder prop="standbyMobile">
              <el-input v-model="form.standbyMobile"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="初登日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.firstRegistrationDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交强日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.clivtaEndDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商业日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.viEndDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')" icon="el-icon-close" size="mini">取 消</el-button>
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="create('form')"
          icon="el-icon-check"
          size="mini"
        >确 定</el-button>
        <el-button
          v-else
          type="primary"
          @click="update('form')"
          icon="el-icon-check"
          size="mini"
        >修 改</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  getTreeData,
  importData,
  getAassignList,
  assignData,
  batchDelObj,
  insertBookingByClientId,
  batchMoveSellData
} from "@/api/customer";

import * as callcenter from "@/api/callcenter";
import * as newcomer from "@/api/newcomer";

import { deptRoleList, fetchDeptTree } from "@/api/role";
import { mapGetters, mapState } from "vuex";
import ElRadioGroup from "element-ui/packages/radio/src/radio-group";
import ElOption from "element-ui/packages/select/src/option";
// Import component
import Loading from "vue-loading-overlay";
// Import stylesheet
import "vue-loading-overlay/dist/vue-loading.css";

import util from "@/libs/util";

export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}

export default {
  name: "销售数据",
  components: {
    ElOption,
    ElRadioGroup,
    Loading
  },
  data() {
    return {
      // 已拨打未拨打
      options7: [
        {
          value: "-1",
          label: "所有"
        },
        {
          value: "0",
          label: "未拨打"
        },
        {
          value: "1",
          label: "已拨打"
      }],
      activeNames: ["1"],
      myHeaders: {},
      uploadParam: {},
      batchRemarks: null,
      isStrict: true,
      reserveDateTime: null,
      // 分配数据
      options: [],
      value: "",
      // 移动数据
      options2: [],
      value2: "",
      // 分类
      options3: [],
      value3: "",
      // 已分配未分配
      options5: [
        {
          label: "所有",
          value: -1
        },
        {
          label: "已分配",
          value: 1
        },
        {
          label: "未分配",
          value: 0
        }
      ],

      // 续保日期
      options4: [
        {
          value: "-1",
          label: "所有"
        },
        {
          value: "30",
          label: "30天"
        },
        {
          value: "60",
          label: "60天"
        },
        {
          value: "90",
          label: "90天"
        }
      ],
      value4: "",
      props: {
        label: "name",
        children: "zones"
      },
      count: 1,
      filename: __filename,
      table: {
        columns: [],
        data: [],
        size: "mini",
        stripe: true,
        border: true
      },
      callList: null,
      isLoading: false,
      treeDeptData: [],
      checkedKeys: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      list: null,
      total: null,
      listQuery: {
        page: 1,
        limit: 50,
        car_owner: null,
        car_no: null,
        client_type: null,
        insEndDate: null
      },
      form: {
        carNo: undefined,
        vehicleNo: undefined,
        engineNumber: undefined,
        carOwner: undefined,
        mobilePhone: undefined,
        vehicleType: undefined,
        firstRegistrationDate: undefined
      },
      rules: {},
      statusOptions: ["0", "1"],
      rolesOptions: [],
      dialogFormVisible: false,
      dialogDetailVisible: false,
      dialogDeptVisible: false,
      dialogImportExcelVisible: false,
      dialogAssignVisible: false,
      userAdd: false,
      userUpd: false,
      userDel: false,
      dialogStatus: "",
      textMap: {
        update: "编辑客户信息",
        create: "新增客户信息",
        import: "导入业务数据",
        assign: "分配业务数据"
      },
      isDisabled: {
        0: false,
        1: true
      },
      tableKey: 0,
      multipleSelection: []
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: "有效",
        1: "无效",
        9: "锁定"
      };
      return statusMap[status];
    }
  },
  computed: {
    // ...mapGetters(['permissions']),
    ...mapState("d2admin/user", ["info"]),
    _token: {
      get: function() {
        return "Bearer " + util.cookies.get("token");
      }
    }
  },
  created() {
    
    this.sys_user_add = this.hasFunctions(["sys_user_add"]);
    this.sys_user_upd = this.hasFunctions(["sys_user_upd"]);
    this.sys_user_del = this.hasFunctions(["sys_user_del"]);

    this.customer_import = this.hasFunctions(["customer_import"]);
    this.customer_export = this.hasFunctions(["customer_export"]);
    this.coustomer_delete = this.hasFunctions(["coustomer_delete"]);
    this.coustomer_batch_delete = this.hasFunctions(["coustomer_batch_delete"]);
    this.coustomer_distribution = this.hasFunctions(["coustomer_distribution"]);

    getAassignList().then(resp => {
      console.log(resp);
      this.options = resp.result;
    });

    newcomer.queryDictListByType("clientGrouping").then(resp => {
      console.log(resp);
      this.options2 = resp;
    });

    newcomer.queryDictListByType("clientType").then(resp => {
      console.log(resp);
      this.options3 = resp.records;
    });

    this.listQuery.success = -1;
    this.getList();
  },
  methods: {
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },

    handleFilter() {
      let tmp = this.listQuery.viEndDate;
      if(tmp != undefined) {
        this.listQuery.viEndDate = tmp[0];
        this.listQuery.viEndDateEnd = tmp[1];
      }

      tmp = this.listQuery.clivtaEndDate;
      if(tmp != undefined) {
        this.listQuery.clivtaEndDate = tmp[0];
        this.listQuery.clivtaEndDateEnd = tmp[1];
      }

      this.listQuery.page = 1;

      this.getList();
    },

    sortChange(_column) {

      this.listQuery.orderByField = _column.prop;
      if(_column.order == "descending")
        this.listQuery.isAsc = false;
      else
        this.listQuery.isAsc = true;

      this.getList();
    },

    getList() {
      this.isLoading = true;
      this.listQuery.isAsc = false;
      fetchList(this.listQuery).then(response => {
        this.list = response.records;
        this.total = response.total;
        this.isLoading = false;
      });
    },
    
    handleCreate() {
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },

    create(formName) {
      const set = this.$refs;
      this.form.role = this.role;
      set[formName].validate(valid => {
        if (valid) {
          this.form.userId = this.info.id;

          addObj(this.form).then(resp => {
            debugger
            if (
              resp.errorMessage != undefined &&
              resp.errorMessage.indexOf("重复") > 0
            ) {
              this.$notify({
                title: "提示",
                message: "车牌号重复，如果自己账号下搜不到。可能分配了给别人，联系主管重新分配数据",
                type: "error"
              });
              return;
            }

            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "提示",
              message: "创建成功",
              type: "success"
            });
          });
        } else {
          return false;
        }
      });
    },

    cancel(formName) {
      this.dialogFormVisible = false;
      this.dialogAssignVisible = false;
      this.$refs[formName].resetFields();
    },

    handleDetial(row) {
      if (row.firstRegistrationDate != null)
        row.firstRegistrationDate = row.firstRegistrationDate.split(" ")[0];

      this.$router.push({
        path: "/customer/detail",
        query: { id: row.id, clientName: row.carOwner, obj: row }
      });
    }
  },
  
};
</script>
<style lang="scss" scoped>
.d2-mb {
  float: left;
  margin-right: 20px;
}
.d2-mb .el-button i {
  margin-right: 4px;
}

.el-row {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
